import threading
from abc import ABC, abstractmethod


class BaseService(ABC):
    """所有后台服务的基类"""

    def __init__(self):
        self._thread = None
        self._running = False

    @abstractmethod
    def _run(self):
        """子类必须实现的核心逻辑"""
        pass

    def start(self):
        """启动服务（线程安全）"""
        if not self._running:
            self._running = True
            self._thread = threading.Thread(target=self._run, daemon=True)
            self._thread.start()

    def stop(self):
        """停止服务"""
        self._running = False
        if self._thread:
            self._thread.join(timeout=5)    # 如果超过5秒线程仍在运行, 不再等待，直接继续执行
